<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const isLoading = ref(false); 
const formEl = ref(null);
const courseForm = ref({
  course_name: '',
  courseForm: '',
});

// 表单验证规则保持不变（添加/修改都需要验证）
const rules = ref({
  course_name: [
    { required: true, message: '课程名称为必填项', trigger: ['blur', 'change'] },
    { min: 2, max: 20, message: '课程名称需在 2-20 字符之间', trigger: ['blur', 'change'] }
  ]
});

// 提交添加（修改为 POST 请求）
const handleSubmit = async (formEl: any) => {

  if (!formEl) return;
  try {
    const isValid = await formEl.validate(); // 表单验证
    if (!isValid) return;
    isLoading.value = true;
    // 添加课程使用 POST 请求，无需课程ID
    const res = await axios.post(`http://localhost:3000/courses`, courseForm.value);
    if (res.data.code !== 200) throw new Error(res.data.message); 
    alert('课程添加成功');
    router.push('/home/Courseread'); // 跳转回课程列表
  } catch (err) {
    //@ts-ignore
    const errorMsg = err instanceof Error ? (err.response?.data?.message || err.message) : '课程添加失败';
    alert(`错误：${errorMsg}`);
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="course-update-container">
    <h2>添加课程信息</h2> <!-- 修改页面标题 -->
    <el-form 
      ref="formEl"
      :model="courseForm" 
      :rules="rules"
      label-width="80px"
      v-loading="isLoading"
      element-loading-text="加载中..."
      loading-spinner="el-icon-loading"
      loading-background="rgba(255, 255, 255, 0.9)"
    >
      <el-form-item label="课程名称" prop="course_name">
        <el-input v-model="courseForm.course_name" />
      </el-form-item>
      <el-form-item label="课程描述">
        <el-input 
          v-model="courseForm.courseForm" 
          type="textarea" 
          :rows="5" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit(formEl)">提交添加</el-button> <!-- 修改按钮文字 -->
        <el-button @click="router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.course-update-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}
</style>